package com.wss.lsl.test.driven.part2;

import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import junit.framework.Assert;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.dbunit.DatabaseTestCase;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.junit.Ignore;

public class DbUnitIntegrationTestCase extends DatabaseTestCase {

	private String driverClassName = "org.hsqldb.jdbcDriver";
	private String jdbcUrl = "jdbc:hsqldb:mem:testdb";
	private String jdbcUsername = "sa";
	private String jdbcPassword = "";

	protected Connection getJdbcConnection() throws ClassNotFoundException,
			SQLException {
		Class.forName(driverClassName);
		Connection connection = DriverManager.getConnection(jdbcUrl,
				jdbcUsername, jdbcPassword);
		return connection;
	}

	public DbUnitIntegrationTestCase() {
		System.out.println("执行了一次");

		// 初始化建表脚本
		SQLExec sqlExec = new SQLExec();
		sqlExec.setDriver(driverClassName);
		sqlExec.setUrl(jdbcUrl);
		sqlExec.setUserid(jdbcUsername);
		sqlExec.setPassword(jdbcPassword);
		sqlExec.setDelimiter(";");
		sqlExec.setPrint(true);
		sqlExec.setSrc(new File("sql-script/test/create-table.sql"));
		sqlExec.setProject(new Project());
		sqlExec.execute();
	}

	@Override
	protected IDatabaseConnection getConnection() throws Exception {
		return new DatabaseConnection(getJdbcConnection());
	}

	@Override
	protected IDataSet getDataSet() throws Exception {
		return getDataSet("initial");
	}

	@SuppressWarnings("deprecation")
	protected IDataSet getDataSet(String name) throws Exception {
		String resource = getClass().getSimpleName() + "." + name + ".xml";
		InputStream is = getClass().getResourceAsStream(resource);
		Assert.assertNotNull("Resource " + resource + " not found", is);
		return new FlatXmlDataSet(is);
	}

	@Ignore
	public void test_() {

	}
}
